/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-4-14 下午10:08 Created by dwzhang
 */
package com.jade.framework.base.lang;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;

/**
 * 类装载工具类。
 *
 * @author dwzhang
 * @version 1.0 13-4-14 下午10:08
 */
public class ClassLoaderUtils
{
    /** 返回类装载器 */
    public static final ClassLoader getClassLoader()
    {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader == null) {
            loader = ClassLoader.getSystemClassLoader();
        }
        return loader;
    }

    /**
     * 交换ThreadContextClassLoader
     *
     * @param classLoader 类装载器
     *                    原先的ClassLoader
     */
    public static final ClassLoader switchClassLoader(ClassLoader classLoader)
    {
        Thread thread = Thread.currentThread();
        ClassLoader oldLoader = thread.getContextClassLoader();
        thread.setContextClassLoader(classLoader);
        return oldLoader;
    }

    public static final Enumeration<URL> getResources(String resourceName)
            throws IOException
    {
        return getResources(null, resourceName);
    }

    public static final Enumeration<URL> getResources(ClassLoader loader, String resourceName)
            throws IOException
    {
        if (resourceName.startsWith("/")) {
            resourceName = resourceName.substring(1);
        }
        if (loader == null) {
            loader = getClassLoader();
        }
        return loader.getResources(resourceName);
    }

    public static final InputStream getResourceAsStream(String resourceName)
    {
        return getResourceAsStream(null, resourceName);
    }

    public static final InputStream getResourceAsStream(ClassLoader loader, String resourceName)
    {
        if (resourceName.startsWith("/")) {
            resourceName = resourceName.substring(1);
        }

        if (loader == null) {
            loader = getClassLoader();
        }

        return loader.getResourceAsStream(resourceName);
    }

    public static final URL getResource(String resourceName)
    {
        return getResource(null, resourceName);
    }

    public static final URL getResource(ClassLoader loader, String resourceName)
    {
        if (resourceName.startsWith("/")) {
            resourceName = resourceName.substring(1);
        }
        if (loader == null) {
            loader = getClassLoader();
        }
        return loader.getResource(resourceName);
    }
}
